package br.com.medmark.bean;

import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

import br.com.medmark.model.hibernate.Clinica;
import br.com.medmark.model.hibernate.Consulta;
import br.com.medmark.model.hibernate.Horario;
import br.com.medmark.model.hibernate.Paciente;
import br.com.medmark.model.hibernate.Profissional;
import br.medmark.util.Constantes;
import br.medmark.util.Funcoes;
import br.medmark.util.Persistencia;

@ManagedBean(name = "beanVisualizarHorarios")
@ViewScoped
public class BeanVisualizarHorarios {
	
	
	private static final long serialVersionUID = 8004854145905841563L;

	private ScheduleModel eventModel;
    
    private ScheduleModel lazyEventModel;
 
    private ScheduleEvent event = new DefaultScheduleEvent();
    
    private HttpSession session;
    
    private FacesContext facesContext;
 
    private List<Horario> horarios;
    
    private Horario horario;
      
    private String hora;
    
    private String data;
    
    private boolean edicaoDesabilitada;
    
    

    
	@PostConstruct
    public void init(){
    	
    	facesContext = FacesContext.getCurrentInstance();
		session = (HttpSession) facesContext.getExternalContext().getSession(true);
		
		Clinica clinica = (Clinica) session.getAttribute("clinica");
		if (clinica == null) {
			try {
				FacesContext.getCurrentInstance().getExternalContext().redirect("login/login.xhtml");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			horarios = Persistencia.getInstance().getHorariosClinica(clinica.getCodigo());
	        eventModel = new DefaultScheduleModel();
	        boolean inserir;
	        for (Horario horario : horarios) {			
	        	String primeiroNomeProfissional = horario.getProfissional().getNome().split(" ")[0];
	        	DefaultScheduleEvent evento;      
	        	inserir = false;
	        	if (horario.getTipoHorario() == Constantes.TIPO_HORARIO_ORDEM_CHEGADA) {
	        		if (!Funcoes.ehDataMaior(horario.getHoraInicial(),Calendar.getInstance().getTime())) {
	        			inserir = true;
	        		}
	       			evento = new DefaultScheduleEvent(primeiroNomeProfissional, horario.getHoraInicial(),horario.getHoraFinal());
	        		
				}else{
					if (!Funcoes.ehDataMaior(horario.getDataConsulta(),Calendar.getInstance().getTime())) {
						inserir = true;
					}
					evento = new DefaultScheduleEvent(primeiroNomeProfissional, horario.getDataConsulta(),horario.getDataConsulta());
				}
	        	if (inserir) {
	    
	            	try {
						if (!Funcoes.diferencaMaiorIgualUmDia(Funcoes.formataData(Funcoes.dataString(horario),"dd/MM/yyyy"), Calendar.getInstance().getTime())) {
							/*StringBuilder sb = new StringBuilder();
							sb.append("<style type='text/css'>");
							sb.append(".custom .ui-state-highlight {");
							sb.append("background: yellow !important;");
							sb.append("}");
							sb.append(" </style>");
							  
							evento.setStyleClass(sb.toString());*/
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            	
	            	evento.setId(String.valueOf(horario.getCodigo()));
	            	evento.setData(horario);
	            	eventModel.addEvent(evento);
				}
	        	
	        }
        
      
		}
       
    }   
       
    public void deletaHorario() throws Exception{
    	 
    	horario = (Horario)event.getData();
    	horarios.remove(horario);
    	horario.setRemovido("S");
    	editaHorario();
    	eventModel.deleteEvent(event);
    	
    }
    
    public void editaHorario() throws Exception{
   	 
    	horario = (Horario)event.getData();
    	Persistencia.getInstance().atualizar(horario);
    	
    	
    }
    
    public ScheduleModel getEventModel() {
        return eventModel;
    }
     
    public ScheduleModel getLazyEventModel() {
        return lazyEventModel;
    }
 
    private Calendar today() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
 
        return calendar;
    }
     
    
     
    public ScheduleEvent getEvent() {
        return event;
    }
 
    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }
     
    public void addEvent(ActionEvent actionEvent) {
        if(event.getId() == null)
            eventModel.addEvent(event);
        else
            eventModel.updateEvent(event);
         
        event = new DefaultScheduleEvent();
    }
     
    public void onEventSelect(SelectEvent selectEvent) {
        event = (ScheduleEvent) selectEvent.getObject();
        horario = (Horario)event.getData();
        hora = Funcoes.horarioString(horario);
        data = Funcoes.dataString(horario);
        if (horario.getTipoHorario() == Constantes.TIPO_HORARIO_HORA_MARCADA) {
			edicaoDesabilitada = true;
		}else{
			edicaoDesabilitada = false;
		}
        /*profissional = ((Consulta)event.getData()).getSolicitacao().getHorario().getProfissional();
        hora = Funcoes.horarioString(((Consulta)event.getData()).getSolicitacao().getHorario());
        data = Funcoes.dataString(((Consulta)event.getData()).getSolicitacao().getHorario());
        consulta = ((Consulta)event.getData());*/
        
    }
     
    public void onDateSelect(SelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(), (Date) selectEvent.getObject());
    }
     
    public void onEventMove(ScheduleEntryMoveEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
         
        addMessage(message);
    }
     
    public void onEventResize(ScheduleEntryResizeEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
         
        addMessage(message);
    }
     
    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

	public List<Horario> getHorarios() {
		return horarios;
	}

	public void setConsultas(List<Horario> horarios) {
		this.horarios = horarios;
	}

	public String getHora() {
		return hora;
	}

	public void setHora(String hora) {
		this.hora = hora;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public void setEventModel(ScheduleModel eventModel) {
		this.eventModel = eventModel;
	}

	public Horario getHorario() {
		return horario;
	}

	public void setHorario(Horario horario) {
		this.horario = horario;
	}


	public boolean isEdicaoDesabilitada() {
		return edicaoDesabilitada;
	}

	public void setEdicaoDesabilitada(boolean edicaoDesabilitada) {
		this.edicaoDesabilitada = edicaoDesabilitada;
	}


}
